package com.wuxin.controller.admin;


import com.alibaba.excel.EasyExcel;
import com.wuxin.dto.ExcelDictDTO;
import com.wuxin.entity.Dict;
import com.wuxin.result.Result;
import com.wuxin.service.DictService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.List;

/**
 * <p>
 * 数据字典 前端控制器
 * </p>
 *
 * @author wuxin
 * @since 2025-01-13
 */
@Api(tags = "数据字典管理")
@RestController
@RequestMapping("/admin/core/dict")
public class DictController {

    @Autowired
    private DictService dictService;

    // /admin/core/dict/import
    @ApiOperation("Excel数据字典导入")
    @PostMapping("/import")
    public Result batchImport(
            @ApiParam(value = "Excel文件",required = true)
            @RequestParam("file")MultipartFile file
            ){
        try {
            InputStream inputStream = file.getInputStream();
            dictService.importData(inputStream);
            return Result.ok().message("数据导入成功！");
        } catch (IOException e) {
            e.printStackTrace();
        }
        return Result.error().message("数据导入失败！");
    }


    // /admin/core/dict/export  ??
    @ApiOperation("根据上级的id获取子节点数据列表")
    @GetMapping("/export")
    public Result export(HttpServletResponse response){
        //这个测试不建议使用swgger会出现各种问题
        response.setContentType("application/vnd.ms-excel");
        response.setCharacterEncoding("UTF-8");

        try {
            String fileName = URLEncoder.encode("mydict","UTF-8").replace("\\+","%20");
            //response.setHeader("");
            //以附件形式进行下载
            response.setHeader("content-disposition",
                    "attachment;fileName="+ URLEncoder.encode(fileName+".xlsx","UTF-8"));

            EasyExcel.write(response.getOutputStream(), ExcelDictDTO.class).
                    sheet("数据字典").doWrite(dictService.listData());
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }



    // /admin/core/dict/listByParentId/${parentId}  get

    @ApiOperation("根据上级的id获取子节点数据列表")
    @GetMapping("/listByParentId/{parentId}")
    public Result listByParentId(
            @ApiParam(value = "上级节点id",required = true)
            @PathVariable("parentId")Long parentId
    ){
        List<Dict> dictList = dictService.listByParentId(parentId);
        return Result.ok().data("list",dictList);
    }
}

